import os

import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

from app.api import api_router
from tortoise.contrib.fastapi import register_tortoise

from app.services.prediction_parameters.load_models import model_manager
from app.services.scheduler.scheduler import start_scheduler, update_radiation_data
from app.tortoise_orm_config import TORTOISE_ORM  # 导入配置

app = FastAPI(
    swagger_ui_css_url="https://cdn.bytedance.com/npm/swagger-ui-dist@5/swagger-ui.css",
    swagger_ui_bundle_js_url="https://cdn.bytedance.com/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
    swagger_ui_standalone_preset_js_url="https://cdn.bytedance.com/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js"
)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# @app.on_event("startup")
# async def startup_event():
#     model_manager.load_all(BASE_DIR)
#     start_scheduler()
#     await update_radiation_data()  # 项目启动时立即执行一次

register_tortoise(
    app,
    config=TORTOISE_ORM,       # 直接传配置字典
    generate_schemas=True,
    add_exception_handlers=True,
)
origins = [
    "http://localhost",     # 你前端的地址，开发环境常用
    "http://127.0.0.1",     # 你前端的地址，开发环境常用
    "http://localhost:5173", # React/Vue默认端口
    "http://127.0.0.1:3000",
    "http://127.0.0.1:3000",
    "http://127.0.0.1:5173",
    # 生产环境的话换成你的前端域名
    "https://your-frontend-domain.com",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 或者 ["*"] 允许所有，但不建议生产用 "*"
    allow_credentials=True,
    allow_methods=["*"],    # 允许所有请求方法 GET, POST, DELETE 等
    allow_headers=["*"],    # 允许所有请求头
)

app.include_router(api_router)

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8081)
